package com.example.translateappjava.Service.Doubao;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DoubaoVisionHelper {
    private static final String TAG = "DoubaoVisionHelper";
    private static final String API_URL = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";
    private static final String API_KEY = "157e66f2-0a3c-4320-947f-a52b9adf77f8"; // 替换为您的API密钥
    private static final String MODEL = "doubao-1-5-vision-pro-32k-250115";

    private Context context;
    private DoubaoVisionListener listener;
    private OkHttpClient client;
    private Handler mainHandler; // 添加主线程Handler

    public interface DoubaoVisionListener {
        void onDoubaoVisionResponse(String response, int index);
        void onDoubaoVisionError(String error, int index);
    }

    public DoubaoVisionHelper(Context context) {
        this.context = context;
        this.mainHandler = new Handler(Looper.getMainLooper()); // 初始化主线程Handler
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
    }

    public void setDoubaoVisionListener(DoubaoVisionListener listener) {
        this.listener = listener;
    }

    /**
     * 调用Doubao Vision API分析图片中的菜品
     * @param bitmap 要分析的图片
     * @param index 图片索引
     */
    public void analyzeFood(Bitmap bitmap, int index) {
        try {
            String base64Image = bitmapToBase64(bitmap);

            JSONObject requestJson = new JSONObject();
            requestJson.put("model", MODEL);
            requestJson.put("max_tokens", 1000);
            requestJson.put("temperature", 0.3);

            JSONArray messages = new JSONArray();
            JSONObject message = new JSONObject();
            message.put("role", "user");

            JSONArray content = new JSONArray();

            // 添加文本提示
            JSONObject textContent = new JSONObject();
            textContent.put("type", "text");
            textContent.put("text", "请仔细分析这张图片，识别出图片中所有的菜品、饮料等人类有可能摄入的物体。如果图片中确实包含食物，请列出具体的菜品名称，不要回答额外的无关信息，eg:“苹果，北京烤鸭，菠菜，油茶”。如果图片中没有食物，请回答'无食物'。");
            content.put(textContent);

            // 添加图片内容
            JSONObject imageContent = new JSONObject();
            imageContent.put("type", "image_url");
            JSONObject imageUrl = new JSONObject();
            imageUrl.put("url", "data:image/jpeg;base64," + base64Image);
            imageContent.put("image_url", imageUrl);
            content.put(imageContent);

            message.put("content", content);
            messages.put(message);
            requestJson.put("messages", messages);

            RequestBody body = RequestBody.create(
                    MediaType.parse("application/json"),
                    requestJson.toString()
            );

            Request request = new Request.Builder()
                    .url(API_URL)
                    .addHeader("Authorization", "Bearer " + API_KEY)
                    .addHeader("Content-Type", "application/json")
                    .post(body)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "API call failed", e);
                    // 切换到主线程执行回调
                    mainHandler.post(() -> {
                        if (listener != null) {
                            listener.onDoubaoVisionError("网络请求失败: " + e.getMessage(), index);
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseBody = response.body().string();

                    if (response.isSuccessful()) {
                        try {
                            JSONObject jsonResponse = new JSONObject(responseBody);
                            JSONArray choices = jsonResponse.getJSONArray("choices");

                            if (choices.length() > 0) {
                                JSONObject choice = choices.getJSONObject(0);
                                JSONObject messageObj = choice.getJSONObject("message");
                                String content = messageObj.getString("content");

                                Log.d(TAG, "Doubao Vision response: " + content);

                                // 切换到主线程执行回调
                                final String finalContent = content;
                                mainHandler.post(() -> {
                                    if (listener != null) {
                                        listener.onDoubaoVisionResponse(finalContent, index);
                                    }
                                });
                            } else {
                                mainHandler.post(() -> {
                                    if (listener != null) {
                                        listener.onDoubaoVisionError("API响应格式错误", index);
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, "Failed to parse response", e);
                            mainHandler.post(() -> {
                                if (listener != null) {
                                    listener.onDoubaoVisionError("响应解析失败: " + e.getMessage(), index);
                                }
                            });
                        }
                    } else {
                        Log.e(TAG, "API call unsuccessful: " + response.code() + " " + responseBody);
                        mainHandler.post(() -> {
                            if (listener != null) {
                                listener.onDoubaoVisionError("API调用失败: " + response.code() + " - " + responseBody, index);
                            }
                        });
                    }
                }
            });

        } catch (Exception e) {
            Log.e(TAG, "Error creating request", e);
            if (listener != null) {
                listener.onDoubaoVisionError("请求创建失败: " + e.getMessage(), index);
            }
        }
    }

    /**
     * 将Bitmap转换为Base64字符串
     */
    private String bitmapToBase64(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.NO_WRAP);
    }
}